import { I18nPluralPipe } from '@angular/common';
import { LocalizedString } from '@angular/compiler';
import { Component, ChangeDetectorRef, Input, OnInit, Inject, ViewChild } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { I18NService } from '@core';
import { _HttpClient, ALAIN_I18N_TOKEN, SettingsService } from '@delon/theme';
import format from 'date-fns/format';
import { NzI18nService } from 'ng-zorro-antd/i18n';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalRef, NzModalService } from 'ng-zorro-antd/modal';
import { NzFormatEmitEvent, NzTreeNode, NzTreeNodeOptions } from 'ng-zorro-antd/tree';
import { NzTreeSelectComponent } from 'ng-zorro-antd/tree-select';

import { DbColumns } from '../../../entity/DbColumns';
import { DbColumnsService } from '../../../service/dbcolumns.service';

@Component({
  selector: 'app-column-editer',
  templateUrl: './column-editer.component.html',
  styleUrls: ['./column-editer.component.less']
})
export class ColumnEditerComponent implements OnInit {
  @Input() id?: String;
  @Input() tableId?: String;
  @Input() isEdit?: boolean;

  form: {
    submitting: boolean;
    model: DbColumns;
  } = {
      submitting: false,
      model: new DbColumns()
    };

  formGroup: FormGroup = new FormGroup({});

  constructor(
    private modalRef: NzModalRef,
    private dbColumnsService: DbColumnsService,
    private fb: FormBuilder,
    private msg: NzMessageService,
    @Inject(ALAIN_I18N_TOKEN) private i18n: I18NService,
    private cdr: ChangeDetectorRef
  ) { }

  ngOnInit(): void {
    if (this.isEdit) {
      this.dbColumnsService.get(`${this.id}`).subscribe(res => {
        this.form.model.init(res.data);
        this.cdr.detectChanges();
      });
    } else {
      this.form.model.autoIncrement = 'NO';
      this.form.model.primaryKey = 'NO';
      this.form.model.isNotNull = 'NO';
      this.form.model.isUnique = 'NO';
      this.form.model.dataType = 'VARCHAR';
      this.form.model.dataLength = 45;
      if (this.tableId) {
        this.form.model.tableId = this.tableId;
      }
      this.cdr.detectChanges();
    }
  }

  onClose(e: MouseEvent): void {
    e.preventDefault();
    this.modalRef.destroy({ refresh: false });
  }

  onSubmit(e: MouseEvent): void {
    e.preventDefault();
    this.form.submitting = true;
    this.form.model.trans();

    (this.isEdit ? this.dbColumnsService.update(this.form.model) : this.dbColumnsService.add(this.form.model)).subscribe(res => {
      if (res.code == 0) {
        this.msg.success(this.i18n.fanyi(this.isEdit ? 'mxk.alert.update.success' : 'mxk.alert.add.success'));
      } else {
        this.msg.error(this.i18n.fanyi(this.isEdit ? 'mxk.alert.update.error' : 'mxk.alert.add.error'));
      }
      this.form.submitting = false;
      this.modalRef.destroy({ refresh: true });
      this.cdr.detectChanges();
    });
  }
}
